﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Drawing;

namespace DataLayer
{
    public class StationInfoDataManager
    {
#if remote
        private static string _meteoDictConnectionString = @"server = 127.0.0.1,1433; uid = dt; pwd=dt;Trusted_Connection=no";
#else
        private static string _meteoDictConnectionString = @"server = 192.168.116.101; uid = dt; pwd=dt;Trusted_Connection=no";
#endif



        public static List<Station> GetStationList()
        {
            List<Station> stats = new List<Station>();
            using (SqlConnection con = new SqlConnection(_meteoDictConnectionString))
            {
                using (SqlCommand cmd = new SqlCommand("", con))
                {
                    cmd.CommandText = "select * from [MeteoDict].[dbo].[StationListForObservationMap] where isActive = 1";
                    con.Open();
                    IDataReader idr = cmd.ExecuteReader();

                    while (idr.Read())
                    {
                        Station stat = new Station();
                        stat.Point = new System.Drawing.PointF(Convert.ToSingle(idr["x"]) / 60.0f * (float)Math.PI / 180.0f,
                                                               Convert.ToSingle(idr["y"]) / 60.0f * (float)Math.PI / 180.0f);
                        stat.Index = Convert.ToInt32(idr["sensorIndex"]);
                        stats.Add(stat);

                    }

                }
                return stats;
            }
        }

        public static Dictionary<int, Dictionary<int, double>> GetDistanceMatrix(List<Station> stations)
        {
            Dictionary<int, Dictionary<int, double>> result = new Dictionary<int, Dictionary<int, double>>();

            foreach (Station station in stations)
            {
                result.Add(station.Index, new Dictionary<int, double>());
                foreach (Station station2 in stations)
                {
                    result[station.Index].Add(station2.Index, GetDistance(station.Point, station2.Point));
                }
            }

            return result;
        }

        private static double GetDistance(PointF p1, PointF p2)
        {
            double dist = 0.0;
            double cosd = Math.Sin(p1.Y) * Math.Sin(p2.Y) + Math.Cos(p1.Y) * Math.Cos(p2.Y) * Math.Cos(p1.X - p2.X);
            dist = Math.Acos(cosd) * 6371;
            return dist;
        }
    }
}
